<script setup>
import { computed, ref } from 'vue'
import { useMessage } from 'naive-ui';
import { createLyla } from '@lylajs/web'
import BaseNode from './BaseNode.vue';
const props = defineProps(['id', 'data'])
const uploading = ref(false);
const message = useMessage()
const data = ref([])

const showTable = ref(false)

const { lyla } = createLyla({ context: null })

const columns = computed(() => {
  if (data.value.length == 0){
    return
  }
  let keys = Object.keys(data.value[0])
  let ds = []
  for(let k of keys){
    ds.push({
      title: k,
      key: k.toLowerCase(),
      sorter: (row1, row2) =>  {
        if (typeof row1[k] == "number" ){
          return row1[k] - row2[k]
        }else if (typeof row1[k] == "string"){
          return  row1[k].localeCompare(row2[k])
        }else{
          return 0
        }
      }
    })
  }
  return ds
})


const uploadFile = ({
      file,
      reqdata,
      headers,
      withCredentials,
      action,
      onFinish,
      onError,
      onProgress
    }) => {
    const formData = new FormData();
    if (reqdata) {
        Object.keys(reqdata).forEach((key) => {
            formData.append(
            key,
            reqdata[key]
            );
        });
    }
    // formData.append(file.name, file.file);
    // KeyError: 'file' how to fix this
    formData.append('file', file.file);


    uploading.value = true;
    lyla.post(action, {
        withCredentials,
        headers,
        body: formData,
        onUploadProgress: ({ percent }) => {
            onProgress({ percent: Math.ceil(percent) });
        }
    }).then(({ json }) => {
        uploading.value = false;
        
        for(let item of json.data){
          data.value.push(item)
        }
        message.success(`size: ${data.value.length}`);
        console.log(data.value)
        onFinish();
    }).catch((error) => {
        uploading.value = false;
        console.log(error);
        message.success(error);
        onError();
    });
};


</script>


<template>
  <BaseNode :loading="uploading" v-model:value="data" target :id="props.id" >
      <n-card style="padding: 4px;min-width: 200px; min-height: 100px; max-height: 500px; overflow-y: auto">
          <n-upload
            multiple
            directory-dnd
            action="/upload"
            :max="5"
            :custom-request="uploadFile"
            style="min-width: 200px; min-height: 100px; max-height: 500px; overflow-y: auto"
          >
          
            <n-upload-dragger
                  style="min-width: 200px; min-height: 100px; max-height: 500px; overflow-y: auto"
              >
          
              <n-text v-if="data.data == null" >文件上传， 拖拽到这里 ， 支持 csv, txt,md, xlsx</n-text>
              <n-text v-else >{{ data.name }}</n-text>
            
            </n-upload-dragger>  
          </n-upload>
          <n-button v-if="data.data != null" @click="showTable = true"> 数据量{{ data.data.length }} <code>点击查看详细</code> </n-button>
        </n-card>
        <n-drawer v-model:show="showTable" :width="600"  :placement="placement">
        <n-drawer-content>
          <n-flex><n-button @click="showTable = false">X</n-button></n-flex>
          <n-data-table  v-if="data.data != null" :data="data.data" :columns="columns">
          </n-data-table>
        </n-drawer-content>
      </n-drawer>
  </BaseNode>
</template>
  
<style >
.n-card > .n-card__content:first-child, .n-card > .n-card__footer:first-child{
  padding: 0px;
}

</style>